package org.xmonkey.notifier.model;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;

import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.dom.ASTNode;
import org.xmonkey.Messages;

/**
 * This class represents a List of ordered subscribers.
 * The subscribers will be notified according to the order defined
 * by a specific comparator
 * @author Jappo
 *
 */
public class OrderedSubscribersList extends LinkedList<ISubscriber> {

	private static final long serialVersionUID = 4696328594067189860L;
	
	private static final Comparator<ISubscriber> comparator = new SubscriberComparator();

	public OrderedSubscribersList(OrderedSubscribersList orderedSubscribersList) {
		super(orderedSubscribersList);
	}

	public OrderedSubscribersList() {
		super();
	}

	@Override
	public boolean add(ISubscriber elementToAdd) {
		boolean addition = false;
		if(!this.contains(elementToAdd)){
			addition = super.add(elementToAdd);
			Collections.sort(this, comparator);
		}
		
		return addition;
	}

	@Override
	public boolean remove(Object elementToRemove) {
		boolean removal = super.remove(elementToRemove);
		Collections.sort(this, comparator);
		return removal;
	}
	
	public String toString(){
		StringBuilder stringBuilder = new StringBuilder();
		
		for(int i = 0; i < this.size(); i++){
			ISubscriber subscriber = this.get(i);
			stringBuilder.append(Messages.OrderedSubscribersList_0);
			stringBuilder.append(i+1);
			stringBuilder.append(Messages.OrderedSubscribersList_1);
			stringBuilder.append(subscriber.getSubscriberName());
			stringBuilder.append(Messages.OrderedSubscribersList_2);
			stringBuilder.append(subscriber.getSubscriberOrder());
			stringBuilder.append(Messages.OrderedSubscribersList_3);
		}
	
		return stringBuilder.toString();
	}

	public boolean removeSubscriptionsFor(ISubscriber subscriber) {
		return this.remove(subscriber);
	}

	public void notifyVisit(IProject project, ASTNode node) {
		for(ISubscriber subscriber : this){
			subscriber.reactToVisit(project, node);
		}
	}

}
